package com.hornsun.Quartz;

/**
 * Created by 编译中... on 2018/6/28.
 */

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;


@Configuration
public class QuartzInit implements ApplicationListener<ContextRefreshedEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(QuartzInit.class);

    @Autowired
    private SchedulerFactoryBean schedulerFactory;

    private static final String JOB_GROUP = "organization-data";

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        Scheduler scheduler = schedulerFactory.getScheduler();
        Map<JobDetail, Set<? extends Trigger>> map = new HashMap<>();
        JobDetail onlineJobDetail = newJob(OnlineFormJob.class)
                .withIdentity(OnlineFormJob.class.getSimpleName(), JOB_GROUP)
                .build();
        JobDetail offlineJobDetail = newJob(OfflineFormJob.class)
                .withIdentity(OfflineFormJob.class.getSimpleName(), JOB_GROUP)
                .build();
        // Trigger the job to run now
        Trigger onlineTrigger = newTrigger()
                .withIdentity(OnlineFormJob.class.getSimpleName(), JOB_GROUP)
                .startNow()
                .withSchedule(
                        cronSchedule("0 0/1 * * * ?")
                )
                .build();
        Trigger offlineTrigger = newTrigger()
                .withIdentity(OfflineFormJob.class.getSimpleName(), JOB_GROUP)
                .startNow()
                .withSchedule(
                        cronSchedule("0 0/30 * * * ?")
                )
                .build();
        map.put(onlineJobDetail, toSet(onlineTrigger));
        map.put(offlineJobDetail, toSet(offlineTrigger));

        try {
            scheduler.scheduleJobs(map, true);
        } catch (SchedulerException e) {
            LOGGER.error("初始化JOB发生异常", e);
        }
    }

    private Set<Trigger> toSet(Trigger trigger) {
        Set<Trigger> result = new HashSet<>();
        result.add(trigger);

        return result;
    }
}
